<template>
  <!-- 单面直出 这里的全部都是单面直出的情况 v-if="isDirectOutput" -->
  <section>
    <!--    这已经是一组数据了     -->
    <!-- <div
      :key="groupKey"
      style="margin-bottom: 15px"
      v-for="(groupKey, groupIdx) in Object.keys(shipmentData.ShippingBagOvs)"
    > -->
    <!--      <h3 style="margin: 15px;">订单号: {{groupKey}}</h3>-->
    <div v-if="shipmentData.ShippingBagOvs" style="margin-bottom: 15px">
      <el-button type="primary" icon="el-icon-add" @click="createdBag()"
        >新增包裹</el-button
      >
    </div>
    <div style="margin-bottom: 15px">
      <transition-group :gutter="3" name="list-complete" tag="el-row">
        <!--    一组的每一个格子    -->
        <el-col
          :key="bagCell['BagOrder']"
          :span="6"
          class="list-complete-item"
          style="margin: 3px 3px"
          v-for="(bagCell, bagIdx) in shipmentData.ShippingBagOvs"
        >
          <el-card
            :style="{
              cursor: 'pointer',
              boxSizing: 'borderBox',
              border:
                bagIdx === +curSelBag
                  ? '2px solid #409EFF'
                  : '2px solid #ffffff'
            }"
            @click.native="selectBag(bagCell, bagIdx)"
          >
            <!--     有合并包裹前和后两种不同的显示模板     -->
            <!--     condition one 没有合单的情况    -->
            <div class="bag-wrap">
              <VueBarCode
                :height="25"
                :value="bagCell.Code"
                displayValue="false"
                element-tag="img"
                width="1"
              >
                条形码显示错误!
              </VueBarCode>

              <div>
                <div style="text-align: center">P/L:{{ bagCell.Code }}</div>
                <div style="padding:5px;text-align: center">
                  客户名称： {{ shipmentData.ShopName }}
                </div>
              </div>

              <table v-if="bagCell.ShoShippingBagDetailVos.length === 1">
                <colgroup>
                  <col width="40%" />
                  <col width="20%" />
                  <col width="40%" />
                </colgroup>
                <tr>
                  <td>订单号:</td>
                  <td colspan="2">
                    {{
                      bagCell.ShoShippingBagDetailVos.length &&
                        bagCell.ShoShippingBagDetailVos[0]["OrderProductCode"]
                    }}
                  </td>
                  <!--          getFirstCellProductDes['OrderProductCode']           -->
                </tr>
                <tr>
                  <td>箱号:</td>
                  <td>{{ +bagCell.BagOrder + 1 }}</td>
                  <td>
                    <!--   {{bagCell.ShoShippingBagDetailVos[0]['OrderProductName'] }}-->
                    <count-to
                      :decimals="2"
                      :duration="300"
                      :end-val="
                        bagCell.isWeighing ? weight.newW : bagCell.Weight
                      "
                      :start-val="0"
                      :suffix="weight.newUnit"
                    />
                    <!--          bagCell.isWeighing ? weight.newW : bagCell.Weight     -->
                    <!--                <span>kg</span>-->
                  </td>
                </tr>
                <tr>
                  <td>产品数量:</td>
                  <td colspan="2">
                    <!--    照片产品中的数量的显示视图可以独立出来 (可能有多个)     -->
                    <!--                <DetailOfProductOfBag-->
                    <!--                  :product-details="bagCell.ShoShippingBagDetailVos[0]['ShippingBagDetailDetailVos']"/>-->

                    <!--                {{bagCell.ShoShippingBagDetailVos.length +' / ' +-->
                    <!--                bagCell.ShoShippingBagDetailVos[0]['ShippingBagDetailDetailVos'][0]['IndexEnd']}}-->
                    {{ bagCell.ShoShippingBagDetailVos.length }}
                  </td>
                </tr>
                <tr>
                  <td>照片数量:</td>
                  <td colspan="2">
                    {{
                      bagCell.ShoShippingBagDetailVos[0][
                        "ShippingBagDetailDetailVos"
                      ][0].IndexStart
                    }}-{{
                      bagCell.ShoShippingBagDetailVos[0][
                        "ShippingBagDetailDetailVos"
                      ][0].IndexEnd
                    }}/{{
                      bagCell.ShoShippingBagDetailVos[0][
                        "ShippingBagDetailDetailVos"
                      ][0].AllNum
                    }}
                  </td>
                </tr>
              </table>

              <!--     合单的情况   显示多个产品  -->
              <template v-if="bagCell.ShoShippingBagDetailVos.length > 1">
                <div @scroll="$_clearCellsPopover(bagCell)" class="multi-wrap">
                  <div
                    :key="product.OrderProductId"
                    class="multi-table-wrap"
                    v-for="(product, index) in bagCell.ShoShippingBagDetailVos"
                  >
                    <table>
                      <colgroup>
                        <col width="40%" />
                        <col width="20%" />
                        <col width="40%" />
                      </colgroup>
                      <tr>
                        <td>订单号:</td>
                        <td colspan="2">
                          {{ product.OrderProductCode }}
                        </td>
                        <!--          getFirstCellProductDes['OrderProductCode']           -->
                      </tr>
                      <tr>
                        <td>箱号:</td>
                        <td>{{ +bagCell.BagOrder + 1 }}</td>
                        <td>
                          <!--   {{bagCell.ShoShippingBagDetailVos[0]['OrderProductName'] }}-->
                          <count-to
                            :decimals="2"
                            :duration="300"
                            :end-val="
                              bagCell.isWeighing ? weight.newW : bagCell.Weight
                            "
                            :start-val="0"
                            :suffix="weight.newUnit"
                          />
                          <!--          bagCell.isWeighing ? weight.newW : bagCell.Weight     -->
                          <!--                <span>kg</span>-->
                        </td>
                      </tr>
                      <tr>
                        <td>产品数量:</td>
                        <td colspan="2">
                          <!--    照片产品中的数量的显示视图可以独立出来 (可能有多个)     -->
                          <!--                <DetailOfProductOfBag-->
                          <!--                  :product-details="bagCell.ShoShippingBagDetailVos[0]['ShippingBagDetailDetailVos']"/>-->

                          <!--                {{bagCell.ShoShippingBagDetailVos.length +' / ' +-->
                          <!--                bagCell.ShoShippingBagDetailVos[0]['ShippingBagDetailDetailVos'][0]['IndexEnd']}}-->
                          {{ product.ShippingBagDetailDetailVos.length }}
                        </td>
                      </tr>
                      <tr>
                        <td>照片数量:</td>
                        <td colspan="2">
                          {{
                            product["ShippingBagDetailDetailVos"][0].IndexStart
                          }}-{{
                            product["ShippingBagDetailDetailVos"][0].IndexEnd
                          }}/{{
                            product["ShippingBagDetailDetailVos"][0].AllNum
                          }}
                        </td>
                      </tr>
                    </table>
                  </div>
                </div>
              </template>

              <!--    v-if="bagCell.ShoShippingBagDetailVos[0]['ShippingBagDetailDetailVos'][0].AllNum <= theMinMergerOrder"             -->

              <!--    合单按钮 => from  (把一个包裹的全部产品合并到另一个包裹)     -->
              <div style="position: absolute;right: -10px;top: -10px;">
                <!--           name="el-fade-in"      -->
                <transition
                  enter-active-class="animated zoomIn"
                  leave-active-class="animated zoomOut"
                >
                  <el-button
                    :disabled="idDoingMergeBag"
                    @click="mergeOrderHandle(bagCell)"
                    circle
                    icon="el-icon-menu"
                    key="merge"
                    size="mini"
                    style="position: absolute;right: 0;top: 0"
                    type="primary"
                    v-if="bagCell['isMerge'] === false"
                  />
                  <!-- v-if="bagCell['isMerge'] === false" -->
                  <el-button
                    @click="cancelMergeOrderHandle(bagCell)"
                    circle
                    icon="el-icon-close"
                    key="cancelMerge"
                    size="mini"
                    style="position: absolute;right: 0;top: 0"
                    type="info"
                    v-if="bagCell['isMerge'] === true"
                  />
                  <!-- v-if="bagCell['isMerge'] === true" -->
                </transition>
              </div>

              <!--    合单按钮 => to     -->
              <div style="position: absolute;left: -10px;top: -10px;">
                <transition
                  enter-active-class="animated zoomIn"
                  leave-active-class="animated zoomOut"
                >
                  <el-button
                    @click="merge2OrderHandle(bagCell)"
                    circle
                    icon="el-icon-bottom-left"
                    size="mini"
                    type="success"
                    v-if="isShowMerge2Btn(bagCell, bagIdx)"
                  />
                  />
                  <!--  v-if="isShowMerge2Btn(bagCell,bagIdx,shipmentData.groupByOrderCode[groupKey])"/> -->
                </transition>
              </div>
            </div>
            <div class="weight-btn" style="">
              <transition mode="out-in" name="el-fade-in">
                <div class="btn-wrap" key="end" v-if="bagCell['isWeighing']">
                  <el-button
                    @click.stop="cancelWeighing(bagCell)"
                    size="mini"
                    type="danger"
                    >取消</el-button
                  >
                  <el-button
                    @click.stop="confirmWeighing(bagCell, idx)"
                    size="mini"
                    type="success"
                    >发货</el-button
                  >
                </div>

                <div class="btn-wrap" key="start" v-else>
                  <el-button
                    :disabled="curHasWeighing"
                    @click.stop="startWeighing(bagCell)"
                    size="mini"
                    type="primary"
                    >称重
                  </el-button>
                </div>
              </transition>
            </div>
          </el-card>
        </el-col>
      </transition-group>

      <el-divider />
    </div>
    <!-- </div> -->
  </section>
</template>

<script>
import VueBarCode from "vue-barcode";
import DetailOfProductOfBag from "@/views/productManagement/aComponents/DetailOfProductOfBag";
import {
  AddPackageBag,
  Shippingland,
  ShippingNeedWeight,
  ChangePackageBagDetail
} from "@/api/factoryPresetScan";
import { ERR_OK, getNumByUnit } from "@/utils/commons";
import CountTo from "vue-count-to";
import _ from "lodash";
import hint from "@/mixins/hint";
import { ecOk } from "@/utils/resHelper";
//  new 陆运包装发货
//  (deprecate)内页册打包发货(双面印)
export default {
  name: "InsideVolumePackingConsignment",
  components: { DetailOfProductOfBag, VueBarCode, CountTo },
  mixins: [hint],
  props: {
    //  不在这里判断,外面用动态组件来,这里是只有单面印的
    shipmentData: {
      type: Object,
      default: () => ({})
    }
  },
  computed: {},
  inject: ["shipmentIns"],
  data() {
    const vm = this;
    return {
      curSelBag: -1,
      idDoingMergeBag: false, //  当前是否有正在合单的操作
      weight: {
        // lastW: 0,
        newW: 0.0,
        newUnit: "g"
      },
      curHasWeighing: false,
      outsideConfig: {
        events: ["click"],
        handler(event) {
          vm.blurSelBag();
        },
        middleware(event) {
          //  OP0000004080
          const { placeholder = "", className } = event.target;
          return !(
            "el-input__inner" === className.trim() &&
            "点击此处开始扫描" === placeholder
          );
        }
      }
    };
  },
  created() {
    this.$_clearCellsPopover = _.throttle(this.clearCellsPopover, 100);
    this.listenBalance();
  },

  mounted() {
    // this.$_setBagsMergeProperties(this.shipmentData);
    console.log(this.shipmentData, 306);
  },

  destroyed() {
    //  Remove existing listener
    delete this.$options.sockets.onmessage;
    this.$disconnect();
  },

  methods: {
    //  内页册的包裹中设置参数
    $_setInsideState(shipmentData) {
      console.log(shipmentData);
      if (Object.keys(shipmentData).length === 0) {
        return;
      }
      shipmentData.ShippingBagOvs.forEach((cell, idx, arr) => {
        if (!Reflect.has(cell, "isWeighing")) {
          this.$set(cell, "isWeighing", false);
        }
      });
    },
    //新增包裹
    async createdBag() {
      const { ShippingNo } = this.shipmentData;
      const { Result, Code } = await AddPackageBag({ ShippingNo });
      if (+Code === ERR_OK) {
        //  把包裹的数据添加,因为重新请求scan接口是没有用的  Result

        //  OP0000004069 OP0000004070
        console.log("添加包裹成功");
        console.log(Result);
        this.shipmentData.ShippingBagOvs = [
          ...this.shipmentData.ShippingBagOvs,
          Result
        ];

        this.$_setInsideState(this.shipmentData);
        console.log(this.shipmentData.ShippingBagOvs);

        // const {Result: res, Code} = await GetShippingBag({
        //   shippingBagCode: ShippingNo,
        //   isGetAll: true
        // });

        // this.cellListRef.focus(curSelBag + 1) //  成功的情况才focus最新的一个
        await this.$nextTick();
        // this.cellListRef.focusLast(); //  成功的情况才focus最新的一个

        this.$message.success("创建包裹成功.");
        return Promise.resolve(Result);
      }
    },

    //获取选中包裹添加
    async selectBag(bagCell, idx) {
      this.curSelBag = this.curSelBag === idx ? -1 : idx;
      // setTimeout(_ => {
      //   this.curSelBag = this.curSelBag === idx ? -1 : idx
      // }, 0)
    },
    // selectBag(i) {
    //   console.log(i,381);
    // },

    //  用户点击合并订单      (from btn click)
    mergeOrderHandle(bagCell, product, detail) {
      console.log(bagCell, 313);
      //  false => cancel状态      true => merge2 ready
      // if (Reflect.has(detail, 'isMerge')) {  //  定义响应式对象
      //   this.$set(detail, 'isMerge', false)
      // }
      this.idDoingMergeBag = true; //  当前有正在合单的包裹
      bagCell.isMerge = true;

      //   // fromShippingNo	是	string	源包裹号
      //   // toShippingNo	是	string	　目标包裹号
    },

    cancelMergeOrderHandle(bagCell) {
      this.idDoingMergeBag = false; //  当前有正在合单的包裹
      bagCell.isMerge = false;
    },

    //  get from
    getCurrentMerge() {
      const curGroup = this.shipmentData.ShippingBagOvs;
      const find = curGroup.find(e => e.isMerge === true);
      if (_.isObject(find)) {
        // console.log(find, 373);
        return find;
      }
    },

    delCurrentMerge() {
      const delcurGroup = this.shipmentData.ShippingBagOvs;
      const findIndex = delcurGroup.findIndex(e => e.isMerge === true);
      console.log(findIndex, 371);
      if (findIndex) {
        delcurGroup.splice(findIndex, 1);
        return;
      }
      // for (const [key, curGroup] of Object.entries(
      //   this.shipmentData.ShippingBagOvs
      // )) {
      //   console.log(curGroup, 394);
      //   const findIndex = curGroup.findIndex(e => e.isMerge === true);
      //   if (findIndex) {
      //     curGroup.splice(findIndex, 1);
      //     return;
      //   }
      // }
    },

    //  用户点击合并订单      (to btn click)
    async merge2OrderHandle(toBag) {
      console.log(toBag, 398);
      const fromBag = this.getCurrentMerge();
      console.log(fromBag, 402);

      try {
        console.log("开始合并", 395);
        //  如果不来自同一组,调用合并
        // if (fromBag.OrderBagId !== toBag.OrderBagId) {
        //  调用 合并订单的接口
        // const { default: { Result, Code } } = await import('../mockMergeOrder.js')
        const {
          Result,
          Code,
          ErrorCode,
          Message
        } = await ChangePackageBagDetail({
          fromCode: fromBag.Code,
          toCode: toBag.Code
        });

        if (+Code === 1) {
          if (ecOk(ErrorCode)) {
            this.delCurrentMerge(); //  删除掉旧的(merge from)
            this.setMergedData2(Result); //  合并数据,把新的数据插入到旧的
            console.log("合并完成", 422);
          }
          this.msg({ ErrorCode, Message });
        }

        // } else {
        //   //  调用 均摊接口
        //   const { Result, Code, ErrorCode, Message } = await AveragePackageBagDetail({
        //     fromCode: fromBag.Code,
        //     toCode: toBag.Code
        //   })
        //   if (+Code === 1) {
        //     ecOk(ErrorCode) && Result.forEach(bagCell => void this.setMergedData2(bagCell))  //  合并数据,把新的数据插入到旧的)
        //     this.msg({ ErrorCode, Message })
        //   }
        // }

        fromBag.isMerge = false; //  把from改为false,因为合并包裹完成
        this.shipmentIns.update(); //  重新添加 merge属性
        this.idDoingMergeBag = false; //  当前有正在合单的包裹
      } catch (e) {
        console.log(e);
      } finally {
      }
    },

    // 把服务器返回的数据替换回去 根据code 包裹编号来进行比较
    setMergedData2(newBagCell) {
      console.log(newBagCell, 449);
      const newGroup = this.shipmentData.ShippingBagOvs;
      const needUpdateIdx = newGroup.findIndex(
        bagCell => newBagCell.Code === bagCell.Code
      );
      console.log(needUpdateIdx, 452);
      newGroup[needUpdateIdx] && newGroup.splice(needUpdateIdx, 1, newBagCell);
      // Object.values(this.shipmentData.ShippingBagOvs).forEach(group => {
      //   const needUpdateIdx = group.findIndex(
      //     bagCell => newBagCell.Code === bagCell.Code
      //   );
      //   group[needUpdateIdx] && group.splice(needUpdateIdx, 1, newBagCell);
      // });
    },

    clearCellsPopover(bagCell) {
      console.log("clear popover");
      bagCell.ShoShippingBagDetailVos.forEach(prod => {
        prod.isEdit = false;
      });
    },
    /**
     *  控制 merge target 按钮是否显示
     * @param bagCell
     * @param bagIdx
     * @param cellGroup
     * @return {boolean}
     */
    isShowMerge2Btn(bagCell, bagIdx, cellGroup) {
      //  这种复杂的判断除了责任链模式还能有其他办法?

      //  can not show in self
      if (bagCell.isMerge) {
        return false;
      }

      //  current must be has from btn of active state
      if (!this.idDoingMergeBag) {
        return false;
      }

      //  去掉了均摊,并且全部都可以来进行合并

      //  (还有一种例外,那就是找倒数第二个来均摊)
      // const currentGroupMerge = cellGroup.some(cell => cell.isMerge)
      // if (currentGroupMerge && cellGroup.length > 1) {
      //   if (cellGroup.length - 2 === bagIdx) {
      //     return true
      //   }
      // }

      //  如果当前是最后一个才显示to按钮
      // if (cellGroup.length - 1 !== bagIdx) {
      //   return false
      // }

      //  根据包裹条件判断,如果当前包裹张数超出max,不显示 todo

      return true;
    },
    //  监听nodejs服务,获取秤的重量
    listenBalance() {
      try {
        // vm.$connect('ws://localhost:9090/alternative/connection/', { format: 'json' })
        this.$connect(
          `ws://${(() => {
            const { ws } = this.$route.query;
            if (!ws) {
              return "127.0.0.1:8333";
            }
            return ws === "dev" ? "192.168.2.194:8333" : `${ws}:8333`;
          })()}`
        );
        this.$options.sockets.onmessage = res => {
          const { data } = res;
          this.setDataOrUnit(data);
        };

        this.$options.sockets.onerror = res => {
          console.log(res);
          this.$notify({
            title: "没有检查到称重工具",
            message: this.$createElement(
              "div",
              { style: "color: teal" },
              "你可能没有启动称重程序,请确认你已经正确安装了称重工具."
            ),
            duration: 0,
            type: "warning"
          });
        };
      } catch (e) {
        this.$notify({
          title: "初始化称重工具失败",
          message: this.$createElement(
            "div",
            { style: "color: #ffffff" },
            "检查端口8333是否已经被占用."
          ),
          duration: 0,
          type: "warning"
        });
        console.log(e);
      }
    },

    //  根据ws的消息来设置
    setDataOrUnit(data) {
      // console.log(data);
      // const weightOrUnit = parseFloat(data)
      // if (isNaN(weightOrUnit)) {
      //   this.weight.newUnit = data.trim()
      // } else {
      //   this.weight.newW = parseFloat(data)
      // }

      //  +0000.55kg    test data sample
      const reg = /([+|\-]?\d*\.\d*)([a-z]*)/;
      const [, weight, unit] = data.toString().match(reg);
      console.log(parseFloat(weight), unit);
      this.weight.newUnit = unit;
      this.weight.newW = parseFloat(weight);
    },

    cancelWeighing(bagCell) {
      this.curHasWeighing = false;
      bagCell.isWeighing = false;
    },

    //  用户点击确认发货
    async confirmWeighing(bagCell, idx) {
      // bagCell.isWeighing ? weight.newW : bagCell.Weight
      const { newUnit, newW } = this.weight;

      if (newW <= 0) {
        this.$notify({
          title: "重量不合法",
          message: this.$createElement(
            "div",
            { style: "color: teal" },
            "包箱重量不能为零"
          ),
          type: "info"
        });
        return;
      }

      bagCell.Weight = newW;
      bagCell.isWeighing = false;
      this.curHasWeighing = false;
      const kgWeight = getNumByUnit(newW, newUnit, "kg"); //  转为kg
      console.log(kgWeight);
      try {
        const { Result, Code, Message } = await ShippingNeedWeight({
          shippingBagCode: bagCell.Code, //  是	string	　包裹号
          weight: kgWeight //  是	decimal	　包裹重量
        });
        if (+Code === ERR_OK) {
          this.$message.success(Message);
          this.$message.success(
            "包裹发货完成,正在自动打印包裹单,from_preset.🎶"
          );

          console.log("start print");
          //  print 快递单
          this.shipmentIns.CreateOneFormPages(
            Array.of(Result["ShippingReport"])
          );
          console.log("end print");

          this.blurSelBag(); //  清除当前选择

          //  删除当前发货完成的包裹
          this.shipmentData.ShippingBagOvs.splice(idx, 1);
        }
      } catch (e) {
        console.log(e);
      }
    },

    blurSelBag() {
      this.curSelBag = -1;
    },

    //  同步的方法
    focusLast() {
      this.focus(this.shipmentData.ShippingBagOvs.length - 1);
    },

    //  一般只有用户回车时才去取值,这时下个事件循环已经错过了
    //  这时一定能取到值,但是最好使用micro task,这样更快一些
    //  参考 vue next-tick的实现
    getCurSelBagOrder() {
      return this.shipmentData.ShippingBagOvs[this.curSelBag]["BagOrder"];
    },

    focus(idx) {
      console.log((this.curSelBag = idx));
    },

    //  用户点击准备开始发货
    startWeighing(bagCell) {
      console.log(bagCell);
      bagCell.isWeighing = true;
      this.curHasWeighing = true;
    }

    //  改变当前选中的,用户点击时
    // async changeIconState(bagCell, idx) {
    //   console.log(bagCell, idx);
    //   setTimeout(_ => {
    //     this.curSelBag = this.curSelBag === idx ? -1 : idx;
    //   }, 0);
    // }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/styles/index.scss";

table {
  border-collapse: collapse;
  width: 200px;

  td {
    border: 1px solid $grayColor;
    text-align: center;
    padding: 3px;
  }
}

.weight-btn {
  position: relative;
  bottom: -5px;
  left: 0px;

  .btn-wrap {
    /*position: absolute;*/
    /*left: 0;*/
    /*bottom: 0;*/
  }
}

.bag-wrap {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-width: 207px;
  min-height: 220px;
  position: relative;
}

.multi-wrap {
  height: 110px;
  overflow-y: auto;
  width: 207px;
  @include scrollBar(4px);

  .multi-table-wrap {
    .rotate {
      transform: rotate(-90deg);
      color: #f56c6c;
    }

    /*&:hover{*/
    /*  .el-icon-remove{*/
    /*    opacity: 1;*/
    /*  }*/
    /*}*/

    .el-icon-remove {
      /*opacity: 0;*/
      transition: all 0.3s linear;
      cursor: pointer;
      position: relative;
      right: 5px;
      font-size: 15px;
      outline: none;
    }

    table {
      margin-bottom: 15px;
    }
  }
}
</style>
